package com.jsu.clubmanagementsystem.controller.application;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jsu.clubmanagementsystem.common.BaseResponse;
import com.jsu.clubmanagementsystem.common.ErrorCode;
import com.jsu.clubmanagementsystem.common.PageQueryRequest;
import com.jsu.clubmanagementsystem.common.ResultUtils;
import com.jsu.clubmanagementsystem.constant.UserConstant;
import com.jsu.clubmanagementsystem.exception.BusinessException;
import com.jsu.clubmanagementsystem.model.dto.userapplication.UserApplicationAddRequest;
import com.jsu.clubmanagementsystem.model.dto.userapplication.UserApplicationQueryRequest;
import com.jsu.clubmanagementsystem.model.entity.Activity;
import com.jsu.clubmanagementsystem.model.entity.User;
import com.jsu.clubmanagementsystem.model.entity.UserApplication;
import com.jsu.clubmanagementsystem.model.enums.ApplicationTypeEnum;
import com.jsu.clubmanagementsystem.model.vo.userApplication.UserApplicationVO;
import com.jsu.clubmanagementsystem.service.activity.ActivityService;
import com.jsu.clubmanagementsystem.service.application.UserApplicationService;
import com.jsu.clubmanagementsystem.service.user.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user-application")
public class UserApplicationController {

    @Resource
    private UserApplicationService applicationService;

    @Resource
    private UserService userService;

    @Resource
    private ActivityService activityService;

    /**
     * 提交申请
     *
     * @param addRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addApplication(@RequestBody UserApplicationAddRequest addRequest, HttpServletRequest request) {
        if (addRequest == null || addRequest.getType() == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        Long userId = addRequest.getUserId();
        if (userId == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户参数为空");
        }
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "请求用户不存在");
        }
        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getId().equals(userId)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "申请用户和登录用户不一致");
        }

        return ResultUtils.success(applicationService.processApplication(addRequest));
    }

    /**
     * 查找申请 (封装)
     *
     * @param applicationId
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<UserApplicationVO> getApplicationVoById(long applicationId, HttpServletRequest request) {
        UserApplication application = applicationService.getById(applicationId);
        if (application == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "目标申请不存在");
        }
        UserApplicationVO userApplicationVO = applicationService.getUserApplicationVO(application);

        User loginUser = userService.getLoginUser(request);
        if (loginUser.getUserRole().equals(UserConstant.USER_ROLE_USER) && !application.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH, "非用户本人的申请");
        } else if (loginUser.getUserRole().equals(UserConstant.USER_ROLE_MANAGER)) {
            Integer type = application.getType();
            if (type.equals(ApplicationTypeEnum.JOIN_CLUB.getCode()) ||
                    type.equals(ApplicationTypeEnum.QUIT_CLUB.getCode())) {
                if (!application.getUserId().equals(loginUser.getId()) &&
                        !application.getAdditionalInfo().equals(loginUser.getManagedClubId())) {
                    throw new BusinessException(ErrorCode.NO_AUTH, "非本社团审核的申请");
                }

            } else if (type.equals(ApplicationTypeEnum.ENGAGE_ACTIVITY.getCode()) ||
                    type.equals(ApplicationTypeEnum.QUIT_ACTIVITY.getCode())) {
                List<Activity> activityListOfClub = activityService.getActivityListOfClub(loginUser.getManagedClubId());
                List<Long> activityIdListOfClub = activityListOfClub.stream().map(Activity::getId).toList();
                if (!application.getUserId().equals(loginUser.getId()) &&
                        activityListOfClub.isEmpty()) {
                    throw new BusinessException(ErrorCode.NO_AUTH, "非本社团审核的申请");
                } else if (!application.getUserId().equals(loginUser.getId()) &&
                        !activityIdListOfClub.contains(application.getAdditionalInfo())) {
                    throw new BusinessException(ErrorCode.NO_AUTH, "非本社团审核的申请");
                }

            } else if (type.equals(ApplicationTypeEnum.DELETE_USER.getCode()) &&
                    !application.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH, "非用户本人的申请");
            }
        }
        return ResultUtils.success(userApplicationVO);
    }

    /**
     * 查看申请列表 (分页)
     *
     * @param queryRequest
     * @return
     */
    @PostMapping("/list")
    public BaseResponse<Page<UserApplicationVO>> listApplicationVoByPage(@RequestBody UserApplicationQueryRequest queryRequest, HttpServletRequest request) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }

        User loginUser = userService.getLoginUser(request);
        Long userId = queryRequest.getUserId();
        Page<UserApplicationVO> page = null;
        if (loginUser.getUserRole().equals(UserConstant.USER_ROLE_ADMIN)){
            page = applicationService.listApplicationVOForAdminByPage(queryRequest);
        } else if (userId == null && loginUser.getUserRole().equals(UserConstant.USER_ROLE_MANAGER)){
            page = applicationService.listApplicationVOForManagerByPage(queryRequest, loginUser.getManagedClubId());
        } else {
            queryRequest.setUserId(loginUser.getId());
            page = applicationService.listApplicationVOForUserByPage(queryRequest);
        }
        return ResultUtils.success(page);
    }

    /**
     * 获取用户请求列表(包括查询)
     * @param page
     * @return
     */
    @PostMapping("/listAll")
    public BaseResponse<Page<UserApplication>> getAllUserApplication(@RequestBody PageQueryRequest page){
        return ResultUtils.success(applicationService.getAllUserApplications(page));
    }
    /**
     * 删除用户审核
     */
    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteuserApplication(@RequestParam List<Long> ids){
        applicationService.deleteUserApplications(ids);
        return ResultUtils.success(true);
    }
}
